package com.oauth.auth.interceptors;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.google.appengine.api.users.User;
import com.oauth.auth.shared.AuthUtil;
import com.oauth.logging.OAuthLogger;
import com.oauth.service.members.beans.Member;
import com.oauth.service.members.service.MemberService;

@Component("logInInterceptor")
public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private MemberService mMemberService;

	@Value("${auth.interceptor.exclude}")
	private String excludePatterns;

	private List<Pattern> compiledPatterns = new ArrayList<Pattern>();

	private final OAuthLogger log = OAuthLogger.getLogger(this.getClass());

	@PostConstruct
	public void init() {
		StringTokenizer st = new StringTokenizer(excludePatterns, ",");
		while (st.hasMoreTokens()) {
			String str = st.nextToken();
			compiledPatterns.add(Pattern.compile(str));
		}
	}

	public boolean preHandle(HttpServletRequest pRequest, HttpServletResponse pResponse,
			Object pCommand) throws Exception {

		String pathInfo = pRequest.getRequestURI();
		for (Pattern pattern : compiledPatterns) {
			if (pattern.matcher(pathInfo).matches()) {
				return true;
			}
		}

		User user = (User) pRequest.getAttribute("user");
		if (user == null) {
			// NOTE: This must be POST url.
			if (pRequest.getPathInfo().endsWith(".ajax")) {
				AuthUtil.writeResponse(pRequest, pResponse);
			} else {
				pResponse.sendRedirect("/");
			}
			return false;

		}
		log.debug("Inside login interceptor:" + user.getEmail());

		Member member = mMemberService.getMember(user.getEmail(), true);
		member.setNickName(user.getNickname());

		pRequest.setAttribute("member", member);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle
	 * (javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse, java.lang.Object,
	 * org.springframework.web.servlet.ModelAndView)
	 */
	public void postHandle(HttpServletRequest pRequest, HttpServletResponse pResponse,
			Object pHandler, ModelAndView pModelAndView) throws Exception {
		// Populate environment urls.
		/*
		 * Member member = (Member)pRequest.getAttribute("member");
		 * pModelAndView.addObject("member",member);
		 */
	}

	public void setMemberService(MemberService pMemberService) {
		mMemberService = pMemberService;
	}

}